package com.mogu.user.controller;


import com.aliyuncs.utils.StringUtils;
import com.mogu.entity.TUser;
import com.mogu.user.service.SendSmsService;
import com.mogu.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/send")
public class SendMess {


    @Autowired
    SendSmsService sendSms;
    @Autowired
    UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/send/{phone}")
    public String code(@PathVariable("phone") String phone) {

        //redis
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return phone + ":" + code + "已存在，还没有过期";
        }

        // 生成验证码并且存储到 redis 中
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);

        boolean isSend = sendSms.send(phone, "SMS_192836966", param);

        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 100, TimeUnit.MINUTES);
            return phone + ":" + code + "发送成功！";
        } else {
            return "发送失败！";
        }
    }
    //校验验证码
//    @RequestMapping("/check")
//    @ResponseBody
//    public String CheckCode(String phone, String SmsCode) {
//        if(redisTemplate.opsForValue().get(phone) ==null) {
//            return "验证码不存在或者过期";
//        }
//        String code = redisTemplate.opsForValue().get(phone);
//        if(!code.equals(SmsCode))
//            return "验证码错误";
//        else
//            return "验证码正确";
//
//    }
    //注册
    @PostMapping("/registry")
    public String regist(@RequestBody TUser tUser){

        return userService.regist(tUser);
    }
}
